"""
AI分析服务API接口
"""
from fastapi import APIRouter, Depends, HTTPException, Query, Body
from sqlalchemy.orm import Session
from pydantic import BaseModel, Field
from typing import Dict, Any, List, Optional, Union
import asyncio

from core.database import get_db
from core.logging_config import get_logger, log_api_request
from core.exceptions import AIServiceError, ValidationError
from core.auth import get_current_user, require_permission
from models.user import User
from services.ai_service_manager import ai_service_manager
from services.ai_service_factory import ServiceType, create_service_request

# 路由器
ai_services_router = APIRouter(tags=["AI分析服务"])

# 日志记录器
logger = get_logger("ai_services_api")


class AnalysisRequest(BaseModel):
    """分析请求模型"""
    service_type: str = Field(..., description="服务类型")
    text: str = Field(..., min_length=1, max_length=10000, description="待分析文本")
    parameters: Dict[str, Any] = Field(default_factory=dict, description="额外参数")
    timeout: Optional[int] = Field(None, ge=1, le=300, description="超时时间（秒）")


class AnalysisResponse(BaseModel):
    """分析响应模型"""
    request_id: str
    service_type: str
    success: bool
    data: Dict[str, Any] = Field(default_factory=dict)
    error_message: str = ""
    processing_time: float = 0.0
    metadata: Dict[str, Any] = Field(default_factory=dict)


class ServiceStatusResponse(BaseModel):
    """服务状态响应模型"""
    name: str
    type: str
    status: str
    version: str
    enabled: bool
    uptime: float
    metrics: Dict[str, Any]


class ServiceHealthResponse(BaseModel):
    """服务健康状态响应模型"""
    total_services: int
    healthy_services: int
    unhealthy_services: int
    alerts: Dict[str, Any]
    last_health_check: str


class ServiceMetricsResponse(BaseModel):
    """服务指标响应模型"""
    service_name: str
    period_days: int
    statistics: List[Dict[str, Any]]


class ServiceAlert(BaseModel):
    """服务告警模型"""
    id: str
    service_name: str
    alert_type: str
    level: str
    message: str
    timestamp: str
    resolved: bool
    resolved_at: Optional[str]
    metadata: Dict[str, Any]


@ai_services_router.post("/analyze", response_model=AnalysisResponse)
@log_api_request("analyze_text")
@require_permission("analysis_task:execute")
async def analyze_text(
    request: AnalysisRequest,
    current_user: User = Depends(get_current_user)
):
    """文本分析接口"""
    logger.info(f"文本分析请求: {request.service_type}")
    
    try:
        # 验证服务类型
        try:
            service_type = ServiceType(request.service_type)
        except ValueError:
            raise HTTPException(status_code=400, detail=f"不支持的服务类型: {request.service_type}")
        
        # 处理分析请求
        response = await ai_service_manager.process_request(
            service_type=service_type,
            data={"text": request.text},
            parameters=request.parameters
        )
        
        return AnalysisResponse(
            request_id=response.request_id,
            service_type=response.service_type.value,
            success=response.success,
            data=response.data,
            error_message=response.error_message,
            processing_time=response.processing_time,
            metadata=response.metadata
        )
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"文本分析失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


@ai_services_router.post("/information-extraction", response_model=AnalysisResponse)
@log_api_request("information_extraction")
@require_permission("analysis_task:execute")
async def extract_information(
    text: str = Body(..., min_length=1, max_length=10000, description="待分析文本"),
    parameters: Dict[str, Any] = Body(default_factory=dict),
    current_user: User = Depends(get_current_user)
):
    """信息抽取接口"""
    logger.info("信息抽取请求")
    
    try:
        response = await ai_service_manager.process_request(
            service_type=ServiceType.INFORMATION_EXTRACTION,
            data={"text": text},
            parameters=parameters
        )
        
        return AnalysisResponse(
            request_id=response.request_id,
            service_type=response.service_type.value,
            success=response.success,
            data=response.data,
            error_message=response.error_message,
            processing_time=response.processing_time,
            metadata=response.metadata
        )
        
    except Exception as e:
        logger.error(f"信息抽取失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


@ai_services_router.post("/pollution-type-recognition", response_model=AnalysisResponse)
@log_api_request("pollution_type_recognition")
@require_permission("analysis_task:execute")
async def recognize_pollution_type(
    text: str = Body(..., min_length=1, max_length=10000, description="待分析文本"),
    parameters: Dict[str, Any] = Body(default_factory=dict),
    current_user: User = Depends(get_current_user)
):
    """污染类型识别接口"""
    logger.info("污染类型识别请求")
    
    try:
        response = await ai_service_manager.process_request(
            service_type=ServiceType.POLLUTION_TYPE_RECOGNITION,
            data={"text": text},
            parameters=parameters
        )
        
        return AnalysisResponse(
            request_id=response.request_id,
            service_type=response.service_type.value,
            success=response.success,
            data=response.data,
            error_message=response.error_message,
            processing_time=response.processing_time,
            metadata=response.metadata
        )
        
    except Exception as e:
        logger.error(f"污染类型识别失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


@ai_services_router.get("/status", response_model=List[ServiceStatusResponse])
@log_api_request("get_service_status")
@require_permission("analysis_task:view")
async def get_service_status(
    current_user: User = Depends(get_current_user)
):
    """获取服务状态"""
    logger.info("获取服务状态请求")
    
    try:
        status_data = ai_service_manager.get_service_status()
        
        services = []
        for service_name, service_info in status_data.get("services", {}).items():
            metrics = service_info.get("metrics", {})
            services.append(ServiceStatusResponse(
                name=service_info["name"],
                type=service_info["type"],
                status=service_info["status"],
                version=service_info["version"],
                enabled=service_info["enabled"],
                uptime=service_info["uptime"],
                metrics=metrics
            ))
        
        return services
        
    except Exception as e:
        logger.error(f"获取服务状态失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


@ai_services_router.get("/health", response_model=ServiceHealthResponse)
@log_api_request("get_service_health")
@require_permission("analysis_task:view")
async def get_service_health(
    current_user: User = Depends(get_current_user)
):
    """获取服务健康状态"""
    logger.info("获取服务健康状态请求")
    
    try:
        health_data = ai_service_manager.get_service_health()
        
        return ServiceHealthResponse(
            total_services=health_data["total_services"],
            healthy_services=health_data["healthy_services"],
            unhealthy_services=health_data["unhealthy_services"],
            alerts=health_data["alerts"],
            last_health_check=health_data["last_health_check"]
        )
        
    except Exception as e:
        logger.error(f"获取服务健康状态失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


@ai_services_router.get("/metrics", response_model=Dict[str, Any])
@log_api_request("get_service_metrics")
@require_permission("analysis_task:view")
async def get_service_metrics(
    service_name: Optional[str] = None,
    days: int = Query(7, ge=1, le=90, description="统计天数"),
    current_user: User = Depends(get_current_user)
):
    """获取服务指标"""
    logger.info("获取服务指标请求")
    
    try:
        metrics_data = ai_service_manager.get_service_metrics(service_name, days)
        return metrics_data
        
    except Exception as e:
        logger.error(f"获取服务指标失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


@ai_services_router.get("/alerts", response_model=List[ServiceAlert])
@log_api_request("get_service_alerts")
@require_permission("analysis_task:view")
async def get_service_alerts(
    service_name: Optional[str] = None,
    level: Optional[str] = None,
    resolved: Optional[bool] = None,
    limit: int = Query(50, ge=1, le=200, description="返回数量限制"),
    current_user: User = Depends(get_current_user)
):
    """获取服务告警"""
    logger.info("获取服务告警请求")
    
    try:
        from services.ai_service_manager import AlertLevel
        
        # 转换level参数
        alert_level = None
        if level:
            try:
                alert_level = AlertLevel(level)
            except ValueError:
                raise HTTPException(status_code=400, detail=f"无效的告警级别: {level}")
        
        alerts_data = ai_service_manager.get_alerts(service_name, alert_level, resolved)
        
        # 应用限制
        alerts_data = alerts_data[:limit]
        
        return [ServiceAlert(**alert) for alert in alerts_data]
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取服务告警失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


@ai_services_router.get("/capabilities", response_model=Dict[str, Any])
@log_api_request("get_service_capabilities")
@require_permission("analysis_task:view")
async def get_service_capabilities(
    current_user: User = Depends(get_current_user)
):
    """获取服务能力"""
    logger.info("获取服务能力请求")
    
    try:
        capabilities = ai_service_manager.get_service_capabilities()
        return capabilities
        
    except Exception as e:
        logger.error(f"获取服务能力失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


@ai_services_router.post("/services/{service_name}/restart")
@log_api_request("restart_service")
@require_permission("analysis_task:manage")
async def restart_service(
    service_name: str,
    current_user: User = Depends(get_current_user)
):
    """重启服务"""
    logger.info(f"重启服务请求: {service_name}")
    
    try:
        success = await ai_service_manager.restart_service(service_name)
        
        if success:
            return {"message": f"服务重启成功: {service_name}"}
        else:
            raise HTTPException(status_code=500, detail=f"服务重启失败: {service_name}")
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"重启服务失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


@ai_services_router.get("/services")
@log_api_request("list_services")
@require_permission("analysis_task:view")
async def list_services(
    current_user: User = Depends(get_current_user)
):
    """列出所有可用服务"""
    logger.info("列出服务请求")
    
    try:
        status_data = ai_service_manager.get_service_status()
        
        services = []
        for service_name, service_info in status_data.get("services", {}).items():
            services.append({
                "name": service_info["name"],
                "type": service_info["type"],
                "status": service_info["status"],
                "version": service_info["version"],
                "enabled": service_info["enabled"],
                "uptime": service_info["uptime"]
            })
        
        return {"services": services, "total": len(services)}
        
    except Exception as e:
        logger.error(f"列出服务失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


@ai_services_router.get("/services/{service_name}")
@log_api_request("get_service_detail")
@require_permission("analysis_task:view")
async def get_service_detail(
    service_name: str,
    current_user: User = Depends(get_current_user)
):
    """获取服务详情"""
    logger.info(f"获取服务详情请求: {service_name}")
    
    try:
        status_data = ai_service_manager.get_service_status()
        service_info = status_data.get("services", {}).get(service_name)
        
        if not service_info:
            raise HTTPException(status_code=404, detail=f"服务不存在: {service_name}")
        
        # 获取服务能力
        capabilities = ai_service_manager.get_service_capabilities()
        service_capabilities = capabilities.get(service_name, {})
        
        return {
            "service_info": service_info,
            "capabilities": service_capabilities
        }
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取服务详情失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


@ai_services_router.post("/batch-analyze")
@log_api_request("batch_analyze")
@require_permission("analysis_task:execute")
async def batch_analyze(
    requests: List[AnalysisRequest],
    current_user: User = Depends(get_current_user)
):
    """批量分析接口"""
    logger.info(f"批量分析请求: {len(requests)} 个任务")
    
    try:
        if len(requests) > 100:
            raise HTTPException(status_code=400, detail="批量分析最多支持100个请求")
        
        # 并发处理请求
        tasks = []
        for request in requests:
            try:
                service_type = ServiceType(request.service_type)
                task = ai_service_manager.process_request(
                    service_type=service_type,
                    data={"text": request.text},
                    parameters=request.parameters
                )
                tasks.append(task)
            except ValueError:
                # 跳过无效的服务类型
                continue
        
        if not tasks:
            raise HTTPException(status_code=400, detail="没有有效的分析请求")
        
        # 执行并发处理
        responses = await asyncio.gather(*tasks, return_exceptions=True)
        
        # 处理结果
        results = []
        for i, response in enumerate(responses):
            if isinstance(response, Exception):
                results.append({
                    "request_index": i,
                    "success": False,
                    "error_message": str(response)
                })
            else:
                results.append({
                    "request_index": i,
                    "success": response.success,
                    "data": response.data,
                    "error_message": response.error_message,
                    "processing_time": response.processing_time
                })
        
        return {
            "total_requests": len(requests),
            "successful_requests": sum(1 for r in results if r["success"]),
            "failed_requests": sum(1 for r in results if not r["success"]),
            "results": results
        }
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"批量分析失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


@ai_services_router.get("/test")
@log_api_request("test_ai_services")
@require_permission("analysis_task:view")
async def test_ai_services(
    current_user: User = Depends(get_current_user)
):
    """测试AI服务接口"""
    logger.info("测试AI服务请求")
    
    try:
        # 测试文本
        test_text = "我家附近有一个工厂，每天晚上都排放废气，味道很大，影响我们居民休息。已经持续一个月了，希望能得到解决。"
        
        # 测试信息抽取
        info_extraction_result = await ai_service_manager.process_request(
            service_type=ServiceType.INFORMATION_EXTRACTION,
            data={"text": test_text}
        )
        
        # 测试污染类型识别
        pollution_result = await ai_service_manager.process_request(
            service_type=ServiceType.POLLUTION_TYPE_RECOGNITION,
            data={"text": test_text}
        )
        
        return {
            "test_results": {
                "information_extraction": {
                    "success": info_extraction_result.success,
                    "data": info_extraction_result.data if info_extraction_result.success else None,
                    "error": info_extraction_result.error_message if not info_extraction_result.success else None,
                    "processing_time": info_extraction_result.processing_time
                },
                "pollution_type_recognition": {
                    "success": pollution_result.success,
                    "data": pollution_result.data if pollution_result.success else None,
                    "error": pollution_result.error_message if not pollution_result.success else None,
                    "processing_time": pollution_result.processing_time
                }
            },
            "test_text": test_text
        }
        
    except Exception as e:
        logger.error(f"测试AI服务失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))